<template>
	<view class="container">
		<view class="layout">
			<view class="list-warp">
				<view class="tips">可提现金额{{ state.money }}元</view>
				<uni-forms :modelValue="formData" border label-position="top">
					<uni-forms-item>
						<view class="flex-align-center">
							<uni-easyinput v-model="formData.money" type="digit" :maxlength="state.moneyMaxLeng" :inputBorder="false" placeholder="请输入提现金额"></uni-easyinput>
							<view class="textBtn" @click="all">全部提现</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="账户名称">
						<uni-easyinput v-model="formData.account" type="text" :inputBorder="false" placeholder="请输入账户名称"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="收款账号">
						<uni-easyinput v-model="formData.accountNumber" type="number" :inputBorder="false" placeholder="请输入收款账号"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="开户银行">
						<uni-easyinput v-model="formData.bank" type="text" :inputBorder="false" placeholder="请输入开户行详细到支行"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="开票信息">
						<view class="label">电子普票</view>
						<view class="label">名称: {{ state.invoice.invoice_name }}</view>
						<view class="flex-align-center">
							<view class="label">纳税人识别号: {{ state.invoice.invoice_number }}</view>
							<view class="copy" @click="copy(state.invoice.invoice_number)">复制</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="上传发票">
						<uni-file-picker v-model="state.imageList" @select="onFilesSelect" @delete="onDelete"></uni-file-picker>
					</uni-forms-item>
				</uni-forms>
				<view class="btn-group">
					<view class="btn" @click="tixian">申请提现</view>
				</view>
			</view>
			<view class="list-warp">
				<view class="title">提现说明</view>
				<view class="content">1. 每个月10号提现</view>
				<view class="content">2. 请先上传发票</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { reactive, ref, nextTick, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { get, post, uploadFile } from '@/request/index.js';

const formData = reactive({
	money: '',
	account: '',
	accountNumber: '',
	bank: '',
	fapiao: []
});

const state = reactive({
	type: 0,
	money: 0,
	moneyMaxLeng: 0,
	invoice: {},
	imageList: []
});
//可提现金额
onLoad((option) => {
	state.money = option.money;
	state.type = option.type;
	const userInfo = JSON.parse(uni.getStorageSync('userinfo'));
	state.invoice = userInfo.invoice;
});
//监听输入的提现
watch(
	() => formData.money,
	(newVal) => {
		nextTick(() => {
			let val = newVal.toString();
			val = val.replace(/[^\d.]/g, ''); //清除"数字"和"."以外的字符
			val = val.replace(/\.{2,}/g, '.'); //只保留第一个. 清除多余的
			val = val.replace(/^0+\./g, '0.');
			val = val.match(/^0+[1-9]+/) ? (val = val.replace(/^0+/g, '')) : val;
			val = val.match(/^\d*(\.?\d{0,2})/g)[0] || '';

			if (val.includes('.')) {
				let numDian = val.toString().split('.')[1].length;
				if (numDian === 2) {
					state.moneyMaxLeng = val.length;
				}
			} else {
				state.moneyMaxLeng = 8;
			}
			formData.money = val;
		});
	}
);
//复制
const copy = (data) => {
	uni.setClipboardData({
		data: data
	});
};
const all = () => {
	formData.money = JSON.parse(JSON.stringify(state.money));
};
//发票图片上传
const onFilesSelect = async (files) => {
	//uni-app, uni-file-picker组件上传有大坑，组件绑定的参数不会更新为接口返回的地址，所以要建两个参数，一个用于组件展示图片用，一个用于提交给后端接口用
	//组件展示图片的地址为临时地址，不是接口返回的服务器上的地址，即使将服务器返回的地址赋值给组件绑定的参数也不行，
	uni.showLoading({
		title: '上传中···'
	});
	const tempFilePaths = files.tempFilePaths;
	const imgUrl = tempFilePaths[0];
	const self = this;
	const res = await uploadFile('agent/Upload/image', imgUrl);
	const { code, data, message } = res;
	if (code == 200) {
		formData.fapiao.push(data.fall_url);
	}
	uni.hideLoading();
};
//删除图片，根据组件绑定的参数（state.imageList）中删除的图片下标，从formData.fapiao中删除对应下标的数据
const onDelete = (e) => {
	const num = e.index;
	formData.fapiao = formData.fapiao.filter((e, i) => i != num);
};
//提交申请提现
const tixian = async () => {
	const { money, account, accountNumber, bank, fapiao } = formData;
	const { money: kmoney, type } = state;
	if (!money.length) {
		return uni.showToast({
			title: '请输入提现金额',
			icon: 'error'
		});
	}
	if (Number(money) > Number(kmoney)) {
		return uni.showToast({
			title: '您输入的金额大于可提现金额，请重新输入！',
			icon: 'none'
		});
	}
	if (!account.length) {
		return uni.showToast({
			title: '请输入账户名称',
			icon: 'error'
		});
	}
	if (!accountNumber.length) {
		return uni.showToast({
			title: '请输入收款账号',
			icon: 'error'
		});
	}
	if (!bank.length) {
		return uni.showToast({
			title: '请输入开户行详细到支行',
			icon: 'none'
		});
	}
	if (!fapiao.length) {
		return uni.showToast({
			title: '请上传发票',
			icon: 'error'
		});
	}
	const params = {
		price: money,
		type: type,
		name: account,
		account: accountNumber,
		bank: bank,
		images: fapiao.join(',')
	};
	const res = await post('agent/withdraw/apply', params);
	if (res.code == 200) {
		uni.showToast({
			title: res.message,
			icon: 'success'
		});
		state.money = (Number(kmoney) - Number(money)).toFixed(2);
		formData.money = '';
		formData.account = '';
		formData.accountNumber = '';
		formData.bank = '';
		formData.fapiao = [];
		state.imageList = [];
		// 提交数据成功后，需要重新请求一下用户信息，因为提现的数据再用户信息中
		getUserInfo();
	}
};
//获取用户信息
const getUserInfo = async () => {
	const res = await get('agent/user/info');
	if (res.code == 200) {
		let userinfo = JSON.parse(uni.getStorageSync('userinfo'));
		userinfo = { ...userinfo, ...res.data };
		uni.setStorageSync('userinfo', JSON.stringify(userinfo));
	}
};
</script>

<style scoped lang="scss">
.uni-forms-item {
	&:first-child {
		::v-deep .uni-forms-item__label {
			display: none;
		}
	}
	::v-deep .is-required {
		display: none;
	}
}
.textBtn {
	font-size: 28rpx;
	color: #5656ff;
}
.btn-group {
	padding: 40rpx 0;
	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 96rpx;
		background-color: #ff5668;
		border-radius: 48rpx;
		font-size: 30rpx;
		color: #fff;
	}
}
.list-warp {
	.label {
		line-height: 50rpx;
		font-size: 28rpx;
		color: #495564;
	}
	.copy {
		font-size: 24rpx;
		color: #ff5668;
	}
	& + .list-warp {
		padding: 32rpx 28rpx;
		margin-top: 20rpx;
	}
	.title {
		height: 70rpx;
		line-height: 42rpx;
		font-size: 28rpx;
	}
	.content {
		font-size: 28rpx;
		color: #666;
		line-height: 48rpx;
	}
}
</style>